/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package desk;

import ejb.ProductManager;
import ejb.RequestManager;
import ejb.Security;
import hibernate.Product;
import hibernate.ProductCategory;
import hibernate.UserRole;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.model.*;

/**
 * Бин добавления запросов
 * @author AGolubinskyy
 */
@ManagedBean(name = "rad")
@RequestScoped
public class RequestAdderBean {

    @ManagedProperty(value="#{th}")
    private TabHolderBean tabHolderBean;
    @ManagedProperty(value = "#{webClientController}")
    private WebClientController clientController;
    private Security security = null;
    private RequestManager requestManager = null;
    private ProductManager productManager = null;
    
    private String message;
    private int product;

    //Создаем неободимый метод для ClientController'а
    public void setClientController(WebClientController clientController) {
        this.clientController = clientController;
        // получаем необходимые объекты
        security = clientController.getServerManager().getSecurity();
        requestManager = clientController.getServerManager().getRequestManager();
        productManager = clientController.getServerManager().getProductManager();
    }

    public List<SelectItem> getProducts() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        List<ProductCategory> cats = productManager.getAllCategories();
        if (cats != null) {
            for (ProductCategory c : cats) {
                items.add(new SelectItem(c.getId(), c.getDescription(), "Category description", true));
                List<Product> prods = productManager.getAllProductsInCategory(c.getId());
                if (prods != null) {
                    for (Product p : prods) {
                        String common="";
                        if (p.isCommon()){
                            common = " (common)";
                        }
                        items.add(new SelectItem(p.getId(), "&nbsp;&nbsp;&nbsp;" + p.getDescription() + common, "Product description", false, false));
                    }
                }
            }
        }
        return items;
    }

    public int getProduct() {
        return product;
    }

    public void setProduct(int product) {
        this.product = product;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    /**
     * Создает запрос. Если запрос созать невозможно, генерирует сообщение FacesMessage
     * @return
     */
    public String submitRequest() throws Exception {
        if (requestManager.create(productManager.getProductByID(product), message)){
            if (security.getCurrentUser().getRole().equals(UserRole.GET_USER_ROLE())){
                tabHolderBean.getTabView().setActiveIndex(1);
            } else {
                tabHolderBean.getTabView().setActiveIndex(0);
            }  
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(security.getCurrentUser().getRole().getRoleName().toLowerCase() + ".jsf");
            } catch (IOException ex) {
                Logger.getLogger(RequestAdderBean.class.getName()).log(Level.SEVERE, null, ex);
            }
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your request created successfully."));
        } else {
            if (security.getCurrentUser().getRole().equals(UserRole.GET_USER_ROLE())){
                tabHolderBean.getTabView().setActiveIndex(0);
            } else {
                tabHolderBean.getTabView().setActiveIndex(1);
            }
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You can't create request for this product."));
        }    
        return null;
    }

    public void setTabHolderBean(TabHolderBean tabHolderBean) {
        this.tabHolderBean = tabHolderBean;
    }
}
